import echarts from 'echarts'

class Time {

  constructor (chart, params = {}) {
    this._chart = chart
    this._params = params
    this._option = null
  }

  render (source) {
    if (!this._option) {
      this._option = this.getOptions({ source, ...this._params })
      this._chart.setOption(this._option)
    } else {
      this._chart.setOption({ series: [{ data: source }] })
    }
  }

  getOptions ({ source, formatter, maxName = '报警值', xAxisType = 'category', maxValue, color = '#708DE8', gradientColor = ['rgba(112, 141, 232, 1)', 'rgba(61, 84, 205, 0)'], gridTop, yAxisName }) {
    const markLine = maxValue ? {
      data: [{
        name: maxName,
        yAxis: maxValue,
        lineStyle: {
          normal: {
            color: '#F91948'
          }
        }
      }]
    } : {}

    return {
      tooltip: {
        trigger: 'axis',
        formatter
      },
      grid: {
        top: gridTop || 20,
        left: '12%',
        bottom: 40,
        right: '5%'
      },
      dataZoom: [
        {
          type: 'inside',
          realtime: true,
          start: 90,
          end: 100
        },
        {
          type: 'slider',
          realtime: true,
          start: 90,
          end: 100
        }
      ],
      xAxis: {
        type: xAxisType,
        boundaryGap: false,
        axisLine: {
          symbol: ['none', 'arrow'],
          symbolSize: [5, 5],
          symbolOffset: [0, 5]
        }
      },
      yAxis: {
        type: 'value',
        name: yAxisName || '',
        boundaryGap: [0, '100%'],
        max: function(value) {
          return parseInt(value.max) * 1.5;
        },
        axisLine: {
          symbol: ['none', 'arrow'],
          symbolSize: [5, 5],
          symbolOffset: [0, 5]
        }
      },
      series: [
        {
          type: 'line',
          smooth: true,
          symbol: 'none',
          sampling: 'average',
          itemStyle: {
            color: color
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: gradientColor[0]
            }, {
              offset: 1,
              color: gradientColor[1]
            }])
          },
          data: source,
          markLine: markLine
        }
      ]
    }
  }
}

export default Time
